package utils;

import service.IUserService;
import service.impl.UserServiceImpl;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

public class NoLoginUtil {
    private static final IUserService userService = new UserServiceImpl();

    public static void doVerify(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        HttpSession session = request.getSession();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("core-data".equals(cookie.getName())) {
                    String value = cookie.getValue();
                    if (!"".equals(value)) {
                        Map<String, String> map = MapUtil.mapString2Map(SecretUtil.decryptBase64(cookie.getValue()));
                        String username = map.get("username");
                        String password = map.get("password");
                        boolean exists = userService.isUserExistsByUsernameAndPassword(username, password);
                        if (exists) {
                            session.setAttribute("username", username);
                            if (userService.isAdminByUsernameAndPassword(username, password)) {
                                session.setAttribute("isAdmin", true);
                            }
                        }
                    }
                }
            }
        }
    }
}